package de.tum.icuproject.persistence.couchdb.select;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import de.tum.icuproject.Subscriber;
import de.tum.icuproject.model.Session;

/**
 * Handles generate session id requests
 * @author stefanoturchetta
 *
 */
public class SessionIdGeneratorRequestHandler extends IdGeneratorRequestHandler {

	public SessionIdGeneratorRequestHandler(Subscriber subscriber) {
		super(subscriber);
	}

	@Override
	protected void notifySubscriber(int id) {
		Subscriber subscriber = this.getSubscriber();
		subscriber.setSessionId(id);
	}

	@Override
	protected int deserializeResult(String result) {
		JsonParser parser = new JsonParser();
		JsonObject root = parser.parse(result).getAsJsonObject();
		JsonArray rows = root.get("rows").getAsJsonArray();
		// if there is nothing inside the array of possible json answers
		if (rows.size() == 0) {
			// return first id
			return 1;
		}
		JsonObject firstObj = rows.get(0).getAsJsonObject();
		JsonObject value = firstObj.get("value").getAsJsonObject();
		Session session = new Gson().fromJson(value, Session.class);
		return session.getSessionId();
	}

}
